#include "SetSerialDialog.h"
#include "qpushbutton.h"
#include <QRegExp>

SetSerialDialog::SetSerialDialog()
{
    this->setWindowTitle("Connection Setup");
    _LoadSettingFromFile();
    _UiInit();
}

SetSerialDialog::~SetSerialDialog()
{

}

void SetSerialDialog::sl_u_buttonBox_clicked(QAbstractButton *button)
{
    if( button
        == dynamic_cast<QAbstractButton*>(u_buttonBox->button(QDialogButtonBox::Ok)) )
    {

        bool ok;
        int responseTime = u_responseTimeLineEdit->text().toInt(&ok,10);
        if(ok == false){
            QMessageBox::about(this, "", "超时时间格式错误");
            return;
        }
        int numberOfRetries = u_numberOfRetriesLineEidt->text().toInt(&ok,10);
        if(ok == false){
            QMessageBox::about(this, "", "重试次数格式错误");
            return;
        }

        if(SerialSettings::ConnectionEnum::Serial
            == (SerialSettings::ConnectionEnum)(u_connectionComboBox->currentIndex()))
        {
            QString portName = u_serialPortCombox->currentText();
            if(portName.size() == 0){
                QMessageBox::about(this,"","请选择一个或取消");
                return;
            }

            g_serialSetting.portName = portName;
            g_serialSetting.parity = u_parityCombox->currentIndex();
            g_serialSetting.baud = u_baudRateCombox->currentData().toInt();
            g_serialSetting.dataBits = u_dataBitsCombox->currentData().toInt();
            g_serialSetting.stopBits = u_stopBitsCombox->currentData().toInt();
        }
        else
        {
            QString ipAddr = u_ipAddressLineEdit->text();
            QRegExp exIP("(25[0-5]|2[0-4]\\d|[0-1]\\d{2}|[1-9]?\\d)"
                       "\\.(25[0-5]|2[0-4]\\d|[0-1]\\d{2}|[1-9]?\\d)"
                       "\\.(25[0-5]|2[0-4]\\d|[0-1]\\d{2}|[1-9]?\\d)"
                       "\\.(25[0-5]|2[0-4]\\d|[0-1]\\d{2}|[1-9]?\\d)");
            QRegExp exUrl("^((https|http|ftp|rtsp|mms)?:\\/\\/)[^\\s]+");

            if( (-1 == exIP.indexIn(ipAddr))
                && (-1 == exUrl.indexIn(ipAddr)) )
            {
                QMessageBox::about(this, "", "the ip format incorrect.");
                return;
            }

            bool ok;
            int port = u_portLineEidt->text().toInt(&ok,10);
            if(ok == false){
                QMessageBox::about(this, "", "the port format incorrect.");
                return;
            }

            g_serialSetting.url = ipAddr;
            g_serialSetting.port = port;
        }
        g_serialSetting.responseTime = responseTime;
        g_serialSetting.numberOfRetries = numberOfRetries;
        g_serialSetting.connectType = (SerialSettings::ConnectionEnum)(u_connectionComboBox->currentIndex());
        accept();
    }
    else if( button
            == dynamic_cast<QAbstractButton*>(u_buttonBox->button(QDialogButtonBox::Cancel)))
    {
        _FillConnectionUi();
        _FillSerialUi();
        _FillTCPIPUi();
        _FillOther();
        hide();
    }
}

void SetSerialDialog::sl_u_connectionGroupBox_currentIndexChanged(int index)
{
    if(index == SerialSettings::ConnectionEnum::Serial){
        u_serialGroupBox->setEnabled(true);
        u_tcpipGroupBox->setEnabled(false);
    } else if( index == SerialSettings::ConnectionEnum::TCP){
        u_serialGroupBox->setEnabled(false);
        u_tcpipGroupBox->setEnabled(true);
    } else{
        u_serialGroupBox->setEnabled(true);
        u_tcpipGroupBox->setEnabled(false);
    }
}

void SetSerialDialog::_UiInit()
{
    u_layout = new QVBoxLayout(this);

    u_buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok|QDialogButtonBox::Cancel
                                       ,this);
    connect(u_buttonBox, &QDialogButtonBox::clicked
            , this, &SetSerialDialog::sl_u_buttonBox_clicked);

    _ConnectionUiInit();
    u_layout->addWidget(u_connectionGroupBox);
    _SerialUiInit();
    u_layout->addWidget(u_serialGroupBox);
    _TCPIPUiInit();
    u_layout->addWidget(u_tcpipGroupBox);
    _OtherUiInit();
    u_layout->addWidget(u_otherGroupBox);
    u_layout->addWidget(u_buttonBox);

    if(g_serialSetting.connectType == SerialSettings::Serial){
        u_tcpipGroupBox->setEnabled(false);
    } else {
        u_serialGroupBox->setEnabled(false);
    }
}

void SetSerialDialog::_ConnectionUiInit()
{
    u_connectionGroupBox = new QGroupBox("Connection",this);
    u_connectionComboBox = new QComboBox(u_connectionGroupBox);

    u_connectionComboBox->addItem("Serial Port");
    u_connectionComboBox->addItem("Modbus TCP/IP");

    QVBoxLayout *layout = new QVBoxLayout(u_connectionGroupBox);
    layout->addWidget(u_connectionComboBox);

    void (QComboBox::*cFun)(int index);
    cFun = &QComboBox::currentIndexChanged;
    connect(u_connectionComboBox, cFun
            , this, &SetSerialDialog::sl_u_connectionGroupBox_currentIndexChanged);

    _FillConnectionUi();
}

void SetSerialDialog::_FillConnectionUi()
{
    u_connectionComboBox->setCurrentIndex(g_serialSetting.connectType);
}

void SetSerialDialog::_SerialUiInit()
{
    u_serialGroupBox = new QGroupBox("Serial Setting",this);
    QVBoxLayout* layout = new QVBoxLayout(u_serialGroupBox);

    // 端口号
    QHBoxLayout *serialPortLayout = new QHBoxLayout();
    QLabel *serialPortLabel = new QLabel("端口号", u_serialGroupBox);
    u_serialPortCombox = new QComboBox(u_serialGroupBox);

    QList<QSerialPortInfo> sList = QSerialPortInfo::availablePorts();
    for(QSerialPortInfo &s:sList) {
        u_serialPortCombox->addItem(s.portName());
    }
    u_serialPortCombox->setCurrentIndex(0);

    serialPortLayout->addWidget(serialPortLabel);
    serialPortLayout->addWidget(u_serialPortCombox);
    layout->addLayout(serialPortLayout);

    // 波特率
    QHBoxLayout *baudRateLayout = new QHBoxLayout();
    QLabel *baudRateLabel = new QLabel("波特率", u_serialGroupBox);
    u_baudRateCombox = new QComboBox(u_serialGroupBox);
    u_baudRateCombox->addItem("1200",QSerialPort::Baud1200);
    u_baudRateCombox->addItem("2400",QSerialPort::Baud2400);
    u_baudRateCombox->addItem("4800",QSerialPort::Baud4800);
    u_baudRateCombox->addItem("9600",QSerialPort::Baud9600);
    u_baudRateCombox->addItem("19200",QSerialPort::Baud19200);
    u_baudRateCombox->addItem("38400",QSerialPort::Baud38400);
    u_baudRateCombox->addItem("57600",QSerialPort::Baud57600);
    u_baudRateCombox->addItem("115200",QSerialPort::Baud115200);
    baudRateLayout->addWidget(baudRateLabel);
    baudRateLayout->addWidget(u_baudRateCombox);
    layout->addLayout(baudRateLayout);

    // 数据位
    QHBoxLayout *dataBitsLayout = new QHBoxLayout();
    QLabel *dataBitsLabel = new QLabel("数据位", u_serialGroupBox);
    u_dataBitsCombox = new QComboBox(u_serialGroupBox);
    u_dataBitsCombox->addItem("5",QSerialPort::Data5);
    u_dataBitsCombox->addItem("6",QSerialPort::Data6);
    u_dataBitsCombox->addItem("7",QSerialPort::Data7);
    u_dataBitsCombox->addItem("8",QSerialPort::Data8);    
    dataBitsLayout->addWidget(dataBitsLabel);
    dataBitsLayout->addWidget(u_dataBitsCombox);
    layout->addLayout(dataBitsLayout);

    // 校验
    QHBoxLayout *parityLayout = new QHBoxLayout();
    QLabel *parityLabel = new QLabel("校验", u_serialGroupBox);
    u_parityCombox = new QComboBox(u_serialGroupBox);
    u_parityCombox->addItem("NoParity");
    u_parityCombox->addItem("EvenParity");
    u_parityCombox->addItem("OddParity");
    u_parityCombox->addItem("SpaceParity");
    u_parityCombox->addItem("MarkParity");
    parityLayout->addWidget(parityLabel);
    parityLayout->addWidget(u_parityCombox);
    layout->addLayout(parityLayout);

    // 停止位
    QHBoxLayout *stopBitsLayout = new QHBoxLayout();
    QLabel *stopBitsLabel = new QLabel("停止位", u_serialGroupBox);
    u_stopBitsCombox = new QComboBox(u_serialGroupBox);
    u_stopBitsCombox->addItem("OneStop",        QSerialPort::OneStop);
    u_stopBitsCombox->addItem("OneAndHalfStop", QSerialPort::OneAndHalfStop);
    u_stopBitsCombox->addItem("TwoStop",        QSerialPort::TwoStop);
    stopBitsLayout->addWidget(stopBitsLabel);
    stopBitsLayout->addWidget(u_stopBitsCombox);
    layout->addLayout(stopBitsLayout);

    QPushButton *refresh = new QPushButton("刷新端口号", u_serialGroupBox);
    connect(refresh, &QPushButton::released, this, [=](){
        u_serialPortCombox->clear();
        QList<QSerialPortInfo> sList = QSerialPortInfo::availablePorts();
        for(QSerialPortInfo &s:sList) {
            u_serialPortCombox->addItem(s.portName());
        }
        u_serialPortCombox->setCurrentIndex(0);
    });
    layout->addWidget(refresh);

    _FillSerialUi();
}

void SetSerialDialog::_FillSerialUi()
{
    // 端口号
    u_serialPortCombox->setCurrentText(g_serialSetting.portName);
    // 波特率
    u_baudRateCombox->setCurrentText(QString::number(g_serialSetting.baud));
    // 数据位
    u_dataBitsCombox->setCurrentText( QString::number(g_serialSetting.dataBits) );
    // 校验
    if(g_serialSetting.parity > QSerialPort::Parity::MarkParity)
        u_parityCombox->setCurrentIndex(0);
    else
        u_parityCombox->setCurrentIndex(g_serialSetting.parity);

    // 停止位
    if(g_serialSetting.stopBits      == QSerialPort::OneStop) u_stopBitsCombox->setCurrentIndex(0);
    else if(g_serialSetting.stopBits == QSerialPort::OneAndHalfStop) u_stopBitsCombox->setCurrentIndex(1);
    else if(g_serialSetting.stopBits == QSerialPort::TwoStop) u_stopBitsCombox->setCurrentIndex(2);
    else u_stopBitsCombox->setCurrentIndex(0);
}

void SetSerialDialog::_TCPIPUiInit()
{
    u_tcpipGroupBox = new QGroupBox("TCP/IP",this);

    QLabel *label1 = new QLabel("IP Address",u_tcpipGroupBox);
    u_ipAddressLineEdit = new QLineEdit(u_tcpipGroupBox);

    QLabel *label2 = new QLabel("Port",u_tcpipGroupBox);
    u_portLineEidt = new QLineEdit(u_tcpipGroupBox);

    QVBoxLayout * layout = new QVBoxLayout(u_tcpipGroupBox);

    layout->addWidget(label1);
    layout->addWidget(u_ipAddressLineEdit);
    layout->addWidget(label2);
    layout->addWidget(u_portLineEidt);

    _FillTCPIPUi();
}

void SetSerialDialog::_FillTCPIPUi()
{
    u_ipAddressLineEdit->setText(g_serialSetting.url);
    u_portLineEidt->setText(QString::number(g_serialSetting.port));
}

void SetSerialDialog::_OtherUiInit()
{
    u_otherGroupBox = new QGroupBox(this);
    QVBoxLayout *layout = new QVBoxLayout(u_otherGroupBox);

    //
    QHBoxLayout *responseTimeLayout = new QHBoxLayout();
    QLabel *responseTimeLabel = new QLabel("发送超时", u_otherGroupBox);
    u_responseTimeLineEdit = new QLineEdit(u_otherGroupBox);
    responseTimeLayout->addWidget(responseTimeLabel);
    responseTimeLayout->addWidget(u_responseTimeLineEdit);
    layout->addLayout(responseTimeLayout);

    //
    QHBoxLayout *numberOfRetriesLayout = new QHBoxLayout();
    QLabel *numberOfRetriesLabel = new QLabel("重试次数", u_otherGroupBox);
    u_numberOfRetriesLineEidt = new QLineEdit(u_otherGroupBox);
    numberOfRetriesLayout->addWidget(numberOfRetriesLabel);
    numberOfRetriesLayout->addWidget(u_numberOfRetriesLineEidt);
    layout->addLayout(numberOfRetriesLayout);

    _FillOther();
}

void SetSerialDialog::_FillOther()
{
    u_responseTimeLineEdit->setText(QString::number(g_serialSetting.responseTime));
    u_numberOfRetriesLineEidt->setText(QString::number(g_serialSetting.numberOfRetries));
}

void SetSerialDialog::_LoadSettingFromFile()
{

}
